<template>
	<view>
		<view style="padding-bottom: 120rpx;">
			<uni-section title="客户信息" type="line">
				<view class="formContainer">
					<uni-forms ref="form">
						<uni-forms-item label="选择客户" required>
							<view @click="chooseCustomer">
								<u--input v-model="fromData.memberName" placeholder="请选择客户" disabled
									disabledColor="#fff" suffixIcon="arrow-right"></u--input>
							</view>
						</uni-forms-item>
						<view v-if="showMemberInfo">
							<uni-forms-item label="客户类型">
								<u--input v-model="memberTypeStr" placeholder="自动带出" disabled
									disabledColor="#fff"></u--input>
							</uni-forms-item>

							<uni-forms-item label="客户来源">
								<u--input v-model="memberSourceStr" placeholder="自动带出" disabled
									disabledColor="#fff"></u--input>
							</uni-forms-item>

							<uni-forms-item label="联系方式">
								<u--input v-model="fromData.contactPhone" placeholder="自动带出" disabled
									disabledColor="#fff"></u--input>
							</uni-forms-item>
						</view>
					</uni-forms>
				</view>
			</uni-section>

			<uni-section title="订单信息" type="line">
				<view class="formContainer">
					<uni-forms ref="form">
						<template v-if="type == 1">
							<uni-forms-item label="是否自定义订单编号" label-width="130">
								<view class="flex-row-center" style="position: relative;top: 16rpx;">
									<text style="margin-right:10rpx;">否</text>
									<u-switch v-model="isCustomOrder" size="15" activeColor="#2879FF"
										@change="fromData.myOrderNo = null"></u-switch>
									<text style="margin-left:10rpx;">是</text>
								</view>
							</uni-forms-item>
							<uni-forms-item v-if="isCustomOrder" label="自定义订单编号" label-width="100">
								<u--input v-model="fromData.myOrderNo" placeholder="请输入自定义订单编号"></u--input>
							</uni-forms-item>
						</template>

						<uni-forms-item label="取车类型" required>
							<!-- <uni-data-checkbox v-model="fromData.rentalType" :localdata="takeCarTypes" /> -->
							<uni-data-select v-model="fromData.rentalType" :localdata="takeCarTypes" :clear="false"
								@change="changeRentalType"></uni-data-select>
							<!-- <hpy-form-select :dataList="takeCarTypes" text="text" name="value" v-model="formData.rentalType"/> -->
						</uni-forms-item>

						<uni-forms-item v-if="fromData.rentalType == 3 || fromData.rentalType == 4" label="取车地址"
							required>
							<view @click="chooseLocation1">
								<u--input v-model="fromData.takeAddress" placeholder="请地图选点" disabled
									disabledColor="#fff" suffixIcon="arrow-right"></u--input>
							</view>
						</uni-forms-item>

						<uni-forms-item v-if="fromData.rentalType == 3 || fromData.rentalType == 5" label="还车地址"
							required>
							<view @click="chooseLocation2">
								<u--input v-model="fromData.alsoAddress" placeholder="请地图选点" suffixIcon="arrow-right"
									disabled disabledColor="#fff"></u--input>
							</view>
						</uni-forms-item>

						<uni-forms-item label="取车门店" required>
							<view @click="showStore1 = !showStore1">
								<u--input v-model="fromData.takeStoreName" placeholder="请选择门店" suffixIcon="arrow-right"
									disabled disabledColor="#fff"></u--input>
							</view>
						</uni-forms-item>

						<uni-forms-item label="还车门店" required>
							<view @click="showStore2 = !showStore2">
								<u--input v-model="fromData.returnStoreName" placeholder="请选择门店"
									suffixIcon="arrow-right" disabled disabledColor="#fff"></u--input>
							</view>
						</uni-forms-item>

						<!--						<uni-forms-item label="租赁时间" required>-->
						<!--							<uni-datetime-picker :value="datetimerange" type="datetimerange" rangeSeparator="至"-->
						<!--								@change="timeChange" />-->
						<!--						</uni-forms-item>-->
						<Timepicker v-model="datetimerange" @change="timeChange"></Timepicker>

						<uni-forms-item label="预订车型" required>
							<view @click="chooseCar">
								<u--input v-model="fromData.modelInfo" placeholder="请选择车型" disabled disabledColor="#fff"
									suffixIcon="arrow-right"></u--input>
							</view>
						</uni-forms-item>

						<uni-forms-item label="订单标签">
							<view class="checkbox-box" style="position: relative;top:-8rpx">
								<uni-data-checkbox mode="tag" multiple v-model="fromData.labels"
									:localdata="labelList"></uni-data-checkbox>
							</view>
						</uni-forms-item>

						<uni-forms-item label="订单来源" required>
							<view @click="showOrderSource = !showOrderSource">
								<u--input v-model="fromData.orderSourceShow" placeholder="请选择订单来源"
									suffixIcon="arrow-right" disabled disabledColor="#fff"></u--input>
							</view>
						</uni-forms-item>
						<!-- 目前只能通过orderSource >=4 来区分是网络订单 -->
						<uni-forms-item v-if="fromData.orderSource >= 4" label="网络订单号" labelWidth="90" required>
							<view><u--input v-model="fromData.networkOrderNo" placeholder="请输入网络订单号"></u--input></view>
						</uni-forms-item>
					</uni-forms>
				</view>
			</uni-section>

			<uni-section title="价格信息" type="line" v-if="showCost">
				<view class="formContainer">
					<uni-forms ref="form">
						<view>
							<uni-forms-item label="车辆押金" required>
								<view>
									<u--input v-model="fromData.deposit" placeholder="自动带出/可修改"
										inputAlign="right"></u--input>
								</view>
							</uni-forms-item>

							<uni-forms-item label="违章押金" required>
								<view>
									<u--input v-model="fromData.illegalDeposit" placeholder="自动带出/可修改"
										inputAlign="right"></u--input>
								</view>
							</uni-forms-item>

							<view v-for="(item, index) in tableData" :key="index" style="margin: 20rpx; ">
								<!-- 费用项标题及操作按钮 -->
								<view class="flex-row-center-sb" style="margin-bottom: 20rpx;">
									<text style="font-size: 28rpx;color: #666;">{{ item.chargeProjectName }}</text>

									<block v-if="item.isRent == 1">
										<text style="font-size: 26rpx;color: #2879FF;"
											@click.stop="showRentDetail = !showRentDetail">
											日租金明细
										</text>
									</block>
									<block v-else>
										<view class="flex-row" v-if="item.canEdit != 1">
											<u-switch v-if="item.isOptional == 1 && item.canEdit != 3"
												v-model="item.selected" size="20"></u-switch>
											<template v-if="item.canEdit == 3">
												<!-- 编辑按钮 -->
												<view style="margin-right: 20rpx;margin-left: 20rpx;"
													@click="editCostItem(2, index, item)">
													<u-icon name="edit-pen" color="#2879FF" size="24"></u-icon>
												</view>
												<!-- 删除按钮 -->
												<view @click="deleteCostItem(index)">
													<u-icon name="trash" color="#2879FF" size="24"></u-icon>
												</view>
											</template>
										</view>
									</block>
								</view>

								<uni-table ref="table" :loading="loading" border stripe>
									<uni-tr>
										<uni-th width="100" align="center">
											<text
												style="color: #2879FF;">单价({{ item.chargeItemsType | chargeItemsType }})</text>
										</uni-th>
										<uni-th width="100" align="center"><text
												style="color: #2879FF;">数目</text></uni-th>
										<uni-th width="100" align="center"><text
												style="color: #2879FF;">费用</text></uni-th>
									</uni-tr>
									<uni-tr>
										<!-- <uni-td align="center">{{ item.unitPrice }}{{ item.chargeItemsType | chargeItemsType }}</uni-td> -->

										<uni-td align="center">
											<template>
												<u--input v-model="item.unitPrice" @input="check" type="digit"
													placeholder="请输入单价"></u--input>
											</template>
										</uni-td>
										<uni-td align="center" v-if="item.canEdit == 2">
											<!-- 按天不可编辑 -->
											<template v-if="item.chargeItemsType == 2">
												{{ item.number }}
											</template>
											<!-- 按次/按个可编辑 -->
											<template v-else>
												<!-- 无上限 -->
												<u-number-box
													v-if="item.upperLimitOfNumber && item.upperLimitOfNumber > 0"
													integer :min="0" :max="item.upperLimitOfNumber"
													v-model="item.number"></u-number-box>
												<!-- 有上限 -->
												<u-number-box v-else integer :min="0"
													v-model="item.number"></u-number-box>
											</template>
										</uni-td>
										<uni-td v-else align="center">{{ item.number }}</uni-td>

										<uni-td align="center">{{ item.chargeMoney }}</uni-td>
									</uni-tr>
								</uni-table>
							</view>

							<view class="flex-xy-center">
								<view class="flex-row-center addCost" @click="editCostItem(1)">
									<u-icon name="plus-circle" color="#fff"></u-icon>
									<text style="color: #fff;font-size: 26rpx;margin-left: 20rpx;">添加收费项</text>
								</view>
							</view>

							<uni-forms-item label="费用合计" required>
								<view><u--input v-model="totalCost" disabled inputAlign="right"></u--input></view>
							</uni-forms-item>

							<uni-forms-item label="实际费用" required>
								<view>
									<u--input v-model="fromData.rent" placeholder="可修改" inputAlign="right"
										@change="changeRent"></u--input>
								</view>
							</uni-forms-item>
							<!-- 优惠金额 -->
							<view class="flex-row-end" v-if="preferentialAmount > 0">
								<text style="color: #E55A5A; font-size: 28rpx;">车辆租赁费优惠{{ preferentialAmount }}元</text>
							</view>

							<uni-forms-item label="费用说明" labelPosition="top">
								<view>
									<u--textarea v-model="fromData.moneyRemark" placeholder="请输入300字以内的费用说明" count
										maxlength="300"></u--textarea>
								</view>
							</uni-forms-item>

							<uni-forms-item label="支付类型" required>
								<uni-data-checkbox v-model="fromData.payType" :localdata="payTypes" />
							</uni-forms-item>
						</view>
					</uni-forms>
				</view>
			</uni-section>

			<uni-section title="其他信息" type="line" v-if="showCost">
				<view class="formContainer">


					<template v-if="orderDetail.orderRemarkList && orderDetail.orderRemarkList.length>0">
						<view class="remarkBox" v-for="(item, index) in orderDetail.orderRemarkList" :key="index">
							<view class="remark">{{ item.remarkContent }}</view>
							<view class="other flex-row-end">
								<text>{{ item.operatorName }}</text>
								<text style="margin-left: 20rpx">{{ item.createTime }}</text>
							</view>
						</view>
					</template>


					<uni-forms ref="form">
						<template v-if="charterService == 1">
							<uni-forms-item label="是否需要代驾" label-width="100">
								<view class="flex-row-center" style="position: relative;top: 16rpx;">
									<text style="margin-right:10rpx;">否</text>
									<u-switch :activeValue='1' :inactiveValue='2' v-model="fromData.isSubstituteDriving"
										size="15" activeColor="#2879FF"></u-switch>
									<text style="margin-left:10rpx;">是</text>
								</view>
							</uni-forms-item>
							<uni-forms-item v-if="fromData.isSubstituteDriving==1" label="选择司机">
								<view @click="chooseDriver">
									<u--input v-model="fromData.substituteDrivingName" placeholder="请选择司机"
										suffixIcon="arrow-right" disabled disabledColor="#fff"></u--input>
								</view>
							</uni-forms-item>
						</template>
						<view>
							<uni-forms-item label="订单说明" labelPosition="top">
								<view>
									<u--textarea v-model="fromData.remark" placeholder="请输入300字以内的订单说明" count
										maxlength="300"></u--textarea>
								</view>
							</uni-forms-item>
						</view>
					</uni-forms>
				</view>
			</uni-section>

			<button type="info" class="sub-btn" @click="confimOrder">{{ type == 1 ? '确认下单' : '保存订单' }}</button>
		</view>

		<!-- 取车门店 -->
		<u-picker :show="showStore1" :columns="storeList" keyName="name" closeOnClickOverlay @close="showStore1 = false"
			@cancel="showStore1 = false" title="取车门店" confirmColor="#1573FF" @confirm="confimStore1"></u-picker>
		<!-- 还车门店 -->
		<u-picker :show="showStore2" :columns="storeList" keyName="name" closeOnClickOverlay @close="showStore2 = false"
			@cancel="showStore2 = false" title="还车门店" confirmColor="#1573FF" @confirm="confimStore2"></u-picker>
		<!-- 订单来源 -->
		<u-picker :show="showOrderSource" :columns="orderSouceList" keyName="name" closeOnClickOverlay
			@close="showOrderSource = false" @cancel="showOrderSource = false" title="订单来源" confirmColor="#1573FF"
			@confirm="confimOrderSource"></u-picker>

		<!-- 新增收费项弹框 -->
		<u-popup :show="showEditCost" mode="bottom" @close="showEditCost = false" closeable round="12">
			<view class="flex-colum-center" style="padding: 40rpx 24rpx 20rpx;">
				<view style="margin-bottom: 30rpx;">{{ popTitleType == 1 ? '新增' : '编辑' }}收费项</view>
				<uni-forms ref="form">
					<uni-forms-item label="收费项名称" labelWidth="90" required>
						<view><u--input v-model="customCost.chargeProjectName" placeholder="请输入收费项名称"></u--input></view>
					</uni-forms-item>

					<uni-forms-item label="收费类型" required>
						<uni-data-checkbox v-model="customCost.chargeItemsType" :localdata="chargeItemsTypes"
							@change="changeType" />
					</uni-forms-item>

					<uni-forms-item label="单价" type="number" labelWidth="90" required>
						<view>
							<u--input v-model="customCost.unitPrice" @input="check" type="digit"
								placeholder="请输入单价"></u--input>
						</view>
					</uni-forms-item>

					<uni-forms-item label="数目" labelWidth="90" required>
						<view>
							<u--input v-model="customCost.number" type="number"
								:disabled="customCost.chargeItemsType == 2 ? true : false"
								placeholder="请输入数量"></u--input>
						</view>
					</uni-forms-item>

					<uni-forms-item label="费用合计" labelWidth="90">
						<view>
							<text
								style="position: relative;top: 15rpx;">{{ customCost.number * customCost.unitPrice || '0' }}</text>
						</view>
					</uni-forms-item>
				</uni-forms>

				<view class="commitBtn" @click="commitCost">提交</view>
			</view>
		</u-popup>

		<u-popup :show="showRentDetail" mode="center" @close="showRentDetail = false" closeable round="12">
			<view class="flex-colum-center" style="padding: 40rpx 24rpx">
				<view style="margin-bottom: 30rpx;">费用租赁明细</view>
				<scroll-view scroll-y="true">
					<view style="max-height: 800rpx;">
						<view class="flex-row-center-sb payCostItem" v-for="(item, index) in fromData.planPriceVoList"
							:key="index">
							<text>{{ item.time }}</text>
							<text>{{ item.price }}元</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>

		<u-modal :show="show" title="提示" :content='alertContent' @confirm="show=false" @close="show=false"
			confirmText="知道了"></u-modal>

		<view class="" v-if="showPage1">
			<page-container :show="showPage1" :overlay="false" @beforeleave="beforeleave('showPage1')"></page-container>
		</view>
	</view>
</template>

<script>
	import {
		orderBasic,
		editOrderBasic,
		getAllLabel,
		confirmationOrder,
		editEchoExpenseItem
	} from '@/api/home-api.js';
	import * as orderApi from '@/api/order-api.js';
	import Timepicker from "@/workbench/order/shortRentOrder/timepicker.vue";
	var moment = require('@/utils/moment.js');
	export default {
		components: {
			Timepicker
		},
		data() {
			return {
				labelList: [],
				show: false,
				alertContent: '',
				showStore1: false, //取车门店弹框
				showStore2: false, //还车门店弹框
				showOrderSource: false, //订单来源弹框
				showCost: false,
				showMemberInfo: false,
				showEditCost: false,
				showOrderTag: false, //订单标签
				showRentDetail: false, //日租金明细
				popTitleType: 1,
				styles: {
					backgroundColor: '#fff'
				},
				takeCarTypes: [{
						value: 1,
						text: '到店取还车'
					},
					{
						value: 3,
						text: '上门送取车'
					},
					{
						value: 4,
						text: '上门送车'
					},
					{
						value: 5,
						text: '上门取车'
					}
				],
				chargeItemsTypes: [{
						value: 1,
						text: '按次'
					},
					{
						value: 2,
						text: '按天'
					},
					{
						value: 6,
						text: '按个'
					}
				],
				payTypes: [{
						value: 2,
						text: '线下支付'
					},
					{
						value: 1,
						text: '小程序支付'
					}
				],
				datetimerange: [moment().format('YYYY-MM-DD HH:mm:ss'), moment()
					.add(2, 'days')
					.format('YYYY-MM-DD HH:mm:ss')
				],
				fromData: {
					myOrderNo: null,
					orderType: 1,
					rentalType: 1, //取车类型,
					takeStoreId: '',
					alsoStoreId: '',
					takeStoreName: '',
					returnStoreName: '',
					rentalStartTime: moment().format('YYYY-MM-DD HH:mm:ss'),
					rentalEndTime: moment()
						.add(2, 'days')
						.format('YYYY-MM-DD HH:mm:ss'),
					takeAddress: '',
					takeLat: 0,
					takeLon: 0,
					alsoAddress: '',
					alsoLat: 0,
					alsoLon: 0,
					planId: '',
					modelInfo: '',
					deposit: '',
					rent: 0,
					illegalDeposit: '',
					chargeItemsVo: [],
					memberNo: '',
					memberName: '',
					memberType: 1,
					memberSource: 1,
					contactPhone: '',
					payType: 2,
					payWay: 1,
					differentStoresCar: 2,
					leaseDays: 0,
					orderSource: 3, //订单来源
					orderSourceShow: '管理端代客下单',
					networkOrderNo: '', //网络订单编号
					remark: '', //订单说明
					moneyRemark: '', //费用说明
					labels: [],
					planPriceVoList: [],
					isSubstituteDriving: 2,
					substituteDrivingId: null,
					substituteDrivingName: null,
				},
				carPlanInfo: {},
				tableData: [],
				currentEditCostIndex: -1,
				customCost: {
					chargeProjectName: '',
					chargeMoney: '',
					chargeItemsType: 1,
					canEdit: 3,
					isRent: 2,
					number: '',
					unitPrice: '',
					calculate: '',
					isOptional: 1,
					selected: true,
					chargeItemsId: null,
					chargeProjectCategory: 9,
					originalPrice: null
				},
				test: '',
				orderNo: '', //编辑订单事使用
				type: 1, //1.新增订单 2.编辑订单
				isCustomOrder: false, //是否自定义订单编号
				orderDetail: {},
				//包车业务新增字段
				showDriver: false,
				showPage1: true, //一开始设置为显示,
				isBackPressed: true,
			};
		},
		computed: {
			charterService() {
				let charterService = this.$store.state.initData.initData.charterService || 2;
				return charterService;
			},
			storeList() {
				var result = [this.$store.state.initData.initData.storeList];
				return result;
			},

			orderSouceList() {
				var orderSource = this.$store.state.initData.initData.orderSource;
				let arr = orderSource.filter(val => Number(val.id) > 2);
				var result = [arr];
				return result;
			},
			memberTypeStr() {
				return this.fromData.memberType == 1 ? '企业' : '个人';
			},
			memberSourceStr() {
				var memberSource = this.fromData.memberSource;
				// return memberSource(memberSource)
				var str = '';
				if (memberSource == 1) {
					str = '搜索';
				} else if (memberSource == 2) {
					str = '分享';
				} else if (memberSource == 3) {
					str = '扫码';
				} else if (memberSource == 4) {
					str = '手动录入';
				} else {
					str = '其他';
				}
				return str;
			},
			// datetimerange() {
			// 	return [this.fromData.rentalStartTime, this.fromData.rentalEndTime];
			// },
			totalCost() {
				var total = 0;
				if (this.tableData.length > 0) {
					this.tableData.map(item => {
						item.selected = item.selected;
						//可编辑
						if (item.canEdit != 1) {
							if (item.chargeItemsType == 2) {
								//按天->开关,无上限限制
								item.chargeMoney = item.number * item.unitPrice;
								item.calculate = item.unitPrice + '×' + item.number;
								return item;
							} else {
								////按次|按个->步进器->有最大金额限制
								if (item.selected && item.number > 0) {
									//当次数|个数大于0时
									const itemCost = item.number * item.unitPrice; //计算出来的金额
									if (item.upperLimitOfAmount != -1) {
										//金额有上限
										if (itemCost > item.upperLimitOfAmount) {
											//当金额大于最大限制金额->取最大金额
											item.chargeMoney = item.upperLimitOfAmount;
											item.calculate = item.unitPrice + '×️' + item.number;
											return item;
										} else {
											//当在最大金额范围内
											item.chargeMoney = item.number * item.unitPrice;
											item.calculate = item.unitPrice + '×' + item.number;
											return item;
										}
									} else {
										//金额无上限
										item.chargeMoney = item.number * item.unitPrice;
										item.calculate = item.unitPrice + '×' + item.number;
										return item;
									}
								} else {
									// item.chargeMoney = 0;
									item.chargeMoney = item.number * item.unitPrice;
									item.calculate = item.unitPrice + '×' + item.number;
									return item;
								}
							}
						} else {
							item.chargeMoney = item.number * item.unitPrice;
							item.calculate = item.unitPrice + '×' + item.number;
							return item;
						}
					});
					this.tableData.map(item => {
						if (item.selected) {
							// console.log('当前收费项金额', item.chargeMoney,'---收费项名称', item.chargeProjectName);
							total += item.chargeMoney;
							// console.log('总金额', total);
						}
					});
				}
				this.fromData.rent = total;
				return total.toFixed(2);
			},
			preferentialAmount() {
				return this.totalCost - this.fromData.rent;
			}
		},
		onBackPress(e) {
			if (!this.isBackPressed) {
				// 如果标志位为 true，表示弹窗已经显示，直接返回 true 禁止默认返回
				return false;
			}

			// 设置标志位为 true，表示弹窗已经显示
			this.isBackPressed = true;
			// 这里可以自定义返回逻辑，比如下面跳转其他页面
			uni.showModal({
				title: `您填写的数据尚未暂存，是否暂存？`,
				success: (e) => {
					if (e.confirm) {
						getApp().globalData.addOrder = this.$data
						//     uni.navigateBack({
						//             delta: 1,
						// });
						// 无论用户点击确定还是取消，重置标志位
						this.isBackPressed = false;
						uni.navigateBack({
							delta: 1,
						});
					} else {
						//点取消，生成新的弹框
						// this.showPage1 = true
						getApp().globalData.addOrder = null

						// 无论用户点击确定还是取消，重置标志位
						this.isBackPressed = false;
						uni.navigateBack({
							delta: 1,
						});
					}
				},
			})
			// return true 表示禁止默认返回
			return true
		},
		onLoad(op) {
			// wx.enableAlertBeforeUnload({
			//   message: '您填写的数据尚未暂存，是否暂存？',
			//   success:function(res){
			//     console.log('success')
			//   },
			//   fail:(e)=>{
			//     console.log('fail')
			//     wx.disableAlertBeforeUnload()
			//     wx.navigateBack()
			//   },
			//   complete:(e)=>{
			//     console.log('complete')
			//   }
			// })
			if (op) {
				this.type = op.type;
				this.orderNo = op.orderNo || '';
				uni.setNavigationBarTitle({
					title: this.type == 2 ? '编辑订单' : '新增订单'
				});
				if (this.type == 2) {
					//编辑订单获取回显数据
					this.getOrderDetail();
				}
			}

			let addOrder = getApp().globalData.addOrder;
			if (addOrder) {
				Object.assign(this.$data, addOrder);
				this.showPage1 = true //一开始设置为显示
				this.isBackPressed = true
			}

			//选择客户监听
			uni.$on('chooseCustomer', data => {
				this.fromData.memberNo = data.memberNo;
				this.fromData.memberName = data.memberName;
				this.fromData.memberType = data.memberType;
				this.fromData.memberSource = data.memberSource;
				this.fromData.contactPhone = data.contactPhone;
				this.showMemberInfo = true;
			});
			//地图选点监听
			uni.$on('chooseLocation', data => {
				if (data.type == 1) {
					this.fromData.takeAddress = data.info.name;
					this.fromData.takeLat = data.info.latitude;
					this.fromData.takeLon = data.info.longitude;
				} else {
					this.fromData.alsoAddress = data.info.name;
					this.fromData.alsoLat = data.info.latitude;
					this.fromData.alsoLon = data.info.longitude;
				}
			});
			//车型方案选择接听
			uni.$on('chooseCarPlan', data => {
				// this.$nextTick(() => {
				this.showCost = true;
				this.carPlanInfo = data;
				this.carPlanInfo.carInfo.modelInfo = data.carInfo.modelInfo;
				this.fromData.modelInfo = data.carInfo.modelInfo;
				this.fromData.planId = data.carInfo.planId;
				this.fromData.planMealId = null;
				this.fromData.leaseDays = data.costInfo.days;
				this.fromData.deposit = data.costInfo.deposit;
				this.fromData.illegalDeposit = data.costInfo.illegalDeposit;
				// this.fromData.rentalEndTime = moment(this.fromData.rentalStartTime)
				// 	.add(this.fromData.leaseDays, 'days')
				// 	.format('YYYY-MM-DD HH:mm:ss');
				if (!uni.$u.test.isEmpty(data.costInfo.chargingItemsVoList)) {
					data.costInfo.chargingItemsVoList.map(item => {
						return this.$set(item, 'selected', true);
					});
				}
				if (!uni.$u.test.isEmpty(data.costInfo.requiredInsurance)) {
					data.costInfo.requiredInsurance.map(item => {
						return this.$set(item, 'selected', true);
					});
				}
				if (!uni.$u.test.isEmpty(data.costInfo.noRequiredInsurance)) {
					data.costInfo.noRequiredInsurance.map(item => {
						return this.$set(item, 'selected', false);
					});
				}
				if (!uni.$u.test.isEmpty(data.costInfo.noMandatoryOtherCostList)) {
					data.costInfo.noMandatoryOtherCostList.map(item => {

						if (item.canEdit == 2) {
							if (item.chargeItemsType != 2) {
								item.number = 1
							}
						}

						this.$set(item, 'selected', false)

						return item;
					});
				}
				this.tableData = [
					...(data.costInfo.chargingItemsVoList || []),
					...(data.costInfo.requiredInsurance || []),
					...(data.costInfo.noRequiredInsurance || []),
					...(data.costInfo.noMandatoryOtherCostList || [])
				];
				this.fromData.planPriceVoList = data.costInfo.planPriceVoList;
				// });
			});
			this.getAllLabel();
		},
		methods: {
			beforeleave() {
				if (this.showPage1) {
					this.showPage1 = false //这个很重要，一定要先把弹框删除掉
					uni.showModal({
						title: `您填写的数据尚未暂存，是否暂存？`,
						success: (e) => {
							if (e.confirm) {
								getApp().globalData.addOrder = this.$data
								uni.navigateBack()
							} else {
								//点取消，生成新的弹框
								// this.showPage1 = true
								getApp().globalData.addOrder = null
								uni.navigateBack()
							}
						},
					})
				} else {
					uni.navigateBack()
				}
			},
			changeRentalType(e) {
				console.log(e);
			},
			// 编辑订单获取回显数据
			getOrderDetail() {
				uni.showLoading();
				orderApi.detail(this.orderNo).then(res => {
					uni.hideLoading();
					this.orderDetail = res.data;
					let orderInfo = res.data.orderInfo;
					let customerInfo = res.data.customerInfo;
					//获取客户信息
					this.showMemberInfo = true;
					this.fromData.memberNo = customerInfo.memberNo;
					this.fromData.memberName = customerInfo.memberName;
					this.fromData.memberType = customerInfo.memberType;
					this.fromData.memberSource = customerInfo.memberSource;
					this.fromData.contactPhone = customerInfo.contactPhone;

					//获取订单信息
					this.showCost = true;
					this.fromData.orderNo = this.orderNo;
					this.fromData.rentalType = orderInfo.rentalType;
					this.fromData.takeStoreId = orderInfo.takeStoreId;
					this.fromData.alsoStoreId = orderInfo.alsoStoreId;
					this.fromData.takeStoreName = orderInfo.takeStoreName;
					this.fromData.returnStoreName = orderInfo.alsoStoreName;
					this.fromData.rentalStartTime = orderInfo.rentalStartTime;
					this.fromData.rentalEndTime = orderInfo.rentalEndTime;
					this.fromData.takeAddress = orderInfo.takeAddress;
					this.fromData.takeLat = orderInfo.takeLat;
					this.fromData.takeLon = orderInfo.takeLon;
					this.fromData.alsoAddress = orderInfo.alsoAddress;
					this.fromData.alsoLat = orderInfo.alsoLat;
					this.fromData.alsoLon = orderInfo.alsoLon;
					this.fromData.planId = orderInfo.planId;
					this.fromData.modelInfo = orderInfo.actualModelName;
					this.fromData.deposit = orderInfo.deposit;
					if (!uni.$u.test.isEmpty(orderInfo.labels)) {
						var labels = orderInfo.labels.split(',');
						var result = [];
						labels.map(item => {
							result.push(Number(item));
						});
						this.fromData.labels = result;
					}
					this.fromData.illegalDeposit = orderInfo.illegalDeposit;
					this.fromData.leaseDays = orderInfo.leaseDays;
					this.fromData.orderSource = orderInfo.orderSource;
					this.fromData.networkOrderNo = orderInfo.networkOrderNo;
					this.fromData.payType = orderInfo.rentPayType;
					this.fromData.payWay = orderInfo.rentPayWay;
					this.fromData.moneyRemark = orderInfo.moneyRemark;
					this.fromData.remark = orderInfo.remark;
					if (this.fromData.takeStoreId != this.fromData.alsoStoreId) {
						this.fromData.differentStoresCar = 1;
					} else {
						this.fromData.differentStoresCar = 2;
					}
					//    let orderChargingItems = res.data.orderChargingItems;
					// orderChargingItems = orderChargingItems.map(item=>{
					// 	this.$set(item, 'selected', true);
					// 	return item;
					// })

					// this.tableData = orderChargingItems;
					setTimeout(() => {
						this.fromData.rent = orderInfo.rent;
					}, 300);
					this.orderSouceList.map(item => {
						if (Number(item.id) === orderInfo.orderSource) {
							this.fromData.orderSourceShow = item.name;
						}
					});
					this.fromData.isSubstituteDriving = orderInfo.isSubstituteDriving;
					this.fromData.substituteDrivingId = orderInfo.substituteDrivingId;
					this.fromData.substituteDrivingName = orderInfo.substituteDrivingName;
					this.getCostInfo();
				});
			},

			check(e) {
				//正则表达试
				e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				this.$nextTick(() => {
					this.customCost.unitPrice = e;
				});
			},

			//编辑回显获取新的方案费用项
			getCostInfo() {
				editEchoExpenseItem(this.orderNo).then(res => {
					this.fromData.planPriceVoList = res.data.planPrice;
					this.tableData = res.data.chargingItems;
				});
			},
			getAllLabel() {
				getAllLabel().then(res => {
					this.labelList = []
					res.data.map(item => {
						this.labelList.push({
							value: item.id,
							text: item.name
						});
					});
				});
			},
			/* 选择客户 */
			chooseCustomer() {
				uni.navigateTo({
					url: './addOrder-customer'
				});
			},
			/* 地图选点:取车地址 */
			chooseLocation1() {
				// uni.navigateTo({
				// 	url: './mapLocation?type=' + type
				// });
				uni.chooseLocation({
					success: res => {
						console.log(res);
						// this.formData.accidentAddress = res.name;
						this.fromData.takeAddress = res.name;
						this.fromData.takeLat = res.latitude;
						this.fromData.takeLon = res.longitude;
					}
				});
			},
			/* 地图选点:还车地址 */
			chooseLocation2() {
				// uni.navigateTo({
				// 	url: './mapLocation?type=' + type
				// });
				uni.chooseLocation({
					success: res => {
						// this.formData.accidentAddress = res.name;
						this.fromData.alsoAddress = res.name;
						this.fromData.alsoLat = res.latitude;
						this.fromData.alsoLon = res.longitude;
					}
				});
			},
			//取车门店
			confimStore1(e) {
				this.fromData.takeStoreId = this.fromData.alsoStoreId = e.value[0].id;
				this.fromData.takeStoreName = this.fromData.returnStoreName = e.value[0].name;
				this.showStore1 = false;
				this.validRntalTime();
			},
			//还车门店
			confimStore2(e) {
				this.fromData.alsoStoreId = e.value[0].id;
				this.fromData.returnStoreName = e.value[0].name;
				this.showStore2 = false;
			},

			validRntalTime() {
				if (!this.$u.test.isEmpty(this.fromData.takeStoreId)) {
					orderApi.validRntalTime({
						takeStoreId: this.fromData.takeStoreId,
						rentalStartTime: this.fromData.rentalStartTime,
						rentalEndTime: this.fromData.rentalEndTime,
						timestamp: moment().valueOf()
					}).then(res => {
						if (res.code == 505) {
							this.show = true;
							this.alertContent = res.msg;
						}
					})
				}

			},

			// 订单来源
			confimOrderSource(e) {
				this.fromData.orderSource = Number(e.value[0].id);
				this.fromData.orderSourceShow = e.value[0].name;
				this.showOrderSource = false;
			},
			/* 租赁时间发生改变 */
			timeChange(e) {
				if (e && Array.isArray(e) && e.length > 1) {
					this.fromData.rentalStartTime = e[0];
					this.fromData.rentalEndTime = e[1];
				} else {
					this.fromData.rentalStartTime = null;
					this.fromData.rentalEndTime = null;
				}

				this.validRntalTime();
				this.resetOrderInfo();
			},
			// 当门店及租赁时间发生改变时重置订单信息
			resetOrderInfo() {
				this.tableData = [];
				this.fromData.planId = null;
				this.fromData.modelInfo = '';
				this.showCost = false;
			},
			//选择车型套餐
			chooseCar() {
				if (this.$u.test.isEmpty(this.fromData.takeStoreId)) {
					this.$u.toast('请选择取车门店');
					return;
				} else if (this.$u.test.isEmpty(this.fromData.alsoStoreId)) {
					this.$u.toast('请选择还车门店');
					return;
				} else if (this.$u.test.isEmpty(this.fromData.rentalStartTime) || this.$u.test.isEmpty(this.fromData
						.rentalEndTime)) {
					this.$u.toast('请选择租赁时间');
					return;
				} else {
					if (this.fromData.takeStoreId != this.fromData.alsoStoreId) {
						this.fromData.differentStoresCar = 1;
					} else {
						this.fromData.differentStoresCar = 2;
					}

					const seconds = moment(this.fromData.rentalEndTime).diff(moment(this.fromData.rentalStartTime),
						'seconds');
					if (seconds <= 14400) {
						this.$u.toast('租赁时间必须大于4小时');
					} else {
						uni.navigateTo({
							url: './addOrder-car' + uni.$u.queryParams(this.fromData)
						});
					}
				}
			},

			//实际费用发生改变
			changeRent(e) {
				var number = Number(e);
				if (e == '') {} else if (number > this.totalCost) {
					this.fromData.rent = this.totalCost;
					this.$u.toast('实际费用不能大于费用合计金额');
				}
			},
			deleteCostItem(index) {
				this.tableData.splice(index, 1);
			},

			// 添加或者编辑自定义费用项
			editCostItem(type, index, info) {
				this.popTitleType = type;
				if (type == 1) {
					//新增
					this.customCost = {
						chargeProjectName: '',
						chargeMoney: '',
						chargeItemsType: 1,
						canEdit: 3,
						isRent: 2,
						number: '',
						unitPrice: '',
						calculate: '',
						isOptional: 1,
						selected: true,
						chargeItemsId: null,
						chargeProjectCategory: 9,
						originalPrice: null
					};
				} else {
					//编辑
					this.customCost = info;
					this.currentEditCostIndex = index;
				}
				this.showEditCost = true;
			},
			changeType(e) {
				console.log(e);
				if (e.detail.value == 2) {
					this.customCost.number = this.fromData.leaseDays;
				}
			},
			//选择司机
			chooseDriver() {
				uni.navigateTo({
					url: './driverList?storeId=' + this.fromData.takeStoreId
				});
				uni.$once('chooseDriverSuccess', (item) => {
					this.fromData.substituteDrivingName = item.nickName;
					this.fromData.substituteDrivingId = item.userId;
				})
			},
			//确定提交费用项
			commitCost() {
				if (uni.$u.test.isEmpty(this.customCost.chargeProjectName)) {
					uni.$u.toast('请输入费用项名称');
					return;
				} else if (uni.$u.test.isEmpty(this.customCost.unitPrice)) {
					uni.$u.toast('请输入单价');
					return;
				} else if (uni.$u.test.isEmpty(this.customCost.number)) {
					uni.$u.toast('请输入数目');
					return;
				} else if (this.customCost.number == '0') {
					uni.$u.toast('数目不能为0,请重新输入');
					return;
				} else {
					if (this.popTitleType == 1) {
						//新增
						this.tableData.push(this.customCost);
					} else {
						//编辑
						this.tableData[this.currentEditCostIndex].chargeProjectName = this.customCost.chargeProjectName;
						this.tableData[this.currentEditCostIndex].unitPrice = this.customCost.unitPrice;
						this.tableData[this.currentEditCostIndex].number = this.customCost.number;
						this.tableData[this.currentEditCostIndex].chargeItemsType = this.customCost.chargeItemsType;
						this.tableData[this.currentEditCostIndex].canEdit = 3;
						this.tableData[this.currentEditCostIndex].chargeMoney =
							Number(this.customCost.unitPrice) * Number(this.customCost.number);
					}

					this.showEditCost = false;
				}
			},

			/* 确认下单 */
			confimOrder() {
				let that = this
				if (this.$u.test.isEmpty(this.fromData.memberNo)) {
					this.$u.toast('请选择客户');
					return;
				} else if (this.$u.test.isEmpty(this.fromData.takeStoreId)) {
					this.$u.toast('请选择取车门店');
					return;
				} else if (this.$u.test.isEmpty(this.fromData.alsoStoreId)) {
					this.$u.toast('请选择还车门店');
					return;
				} else if (
					this.$u.test.isEmpty(this.fromData.takeAddress) &&
					(this.fromData.rentalType == 3 || this.fromData.rentalType == 4)
				) {
					this.$u.toast('请选择取车地址');
					return;
				} else if (
					this.$u.test.isEmpty(this.fromData.alsoAddress) &&
					(this.fromData.rentalType == 3 || this.fromData.rentalType == 5)
				) {
					this.$u.toast('请选择还车地址');
					return;
				} else if (this.$u.test.isEmpty(this.fromData.rentalStartTime) || this.$u.test.isEmpty(this.fromData
						.rentalEndTime)) {
					this.$u.toast('请选择租赁时间');
					return;
				} else if (this.$u.test.isEmpty(this.fromData.planId)) {
					this.$u.toast('请选择预定车型');
					return;
				} else if (this.fromData.orderSource == 0) {
					this.$u.toast('请选择订单来源');
					return;
				} else if (this.fromData.orderSource >= 4 && this.fromData.networkOrderNo == '') {
					this.$u.toast('请输入订单编号');
					return;
				} else {
					this.fromData.chargeItemsVo = this.tableData.filter(item => {
						return item.selected == true && item.chargeMoney != 0;
					});
					this.fromData.preferentialAmount = this.preferentialAmount;
					//短租下单接口
					uni.showLoading({
						title: '提交中...',
						mask: true
					});
					if (this.type == 1) {
						//新增订单
						orderBasic(this.fromData).then(res => {
							uni.hideLoading();
							if (res.code == 200) {
								uni.showToast({
									title: '下单成功',
									duration: 2000,
									complete() {
										getApp().globalData.addOrder = null
										that.showPage1 = false
										that.isBackPressed = false
										uni.navigateBack({});
									}
								});
							} else if (res.code == 505) {
								that.alertContent = res.msg;
								this.show = true;
							}
						});
					} else {
						// 编辑订单
						editOrderBasic(this.fromData).then(res => {
							uni.hideLoading();
							if (res.code == 200) {
								uni.showToast({
									title: '保存成功',
									duration: 2000,
									complete() {
										getApp().globalData.addOrder = null
										uni.$emit('refreshOrder');
										that.showPage1 = false
										that.isBackPressed = false
										uni.navigateBack({});
									}
								});
							} else if (res.code == 505) {
								this.alertContent = res.msg;
								this.show = true;
							}
						});
					}
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import '@/style/helang-table.scss';

	.formContainer {
		margin: 40rpx 20rpx;
		padding: 24rpx;
		background-color: #fff;
		box-shadow: 0px 4rpx 16rpx 0px rgba(1, 10, 18, 0.1);
		border-radius: 16rpx;
	}

	.addCost {
		margin: 32rpx 0;
		box-sizing: border-box;
		padding-left: 30rpx;
		width: 242rpx;
		height: 60rpx;
		background: #1673ff;
		border-radius: 30rpx;
	}

	.commitBtn {
		background-color: #1673ff;
		border-radius: 12rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		width: 300rpx;
		margin-top: 30rpx;
	}

	.payCostItem {
		height: 80rpx;
		width: 600rpx;
		border-bottom: 1rpx solid #ededed;
		font-size: 28rpx;
		color: #333;
	}

	.remarkBox {
		background: #F2F7FF;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-top: 20rpx;

		.remark {
			color: #333333;
			font-size: 28rpx;
		}

		.other {
			margin-top: 20rpx;
			color: #999999;
			font-size: 28rpx;
		}

	}
</style>